/*************************************************************************
> File Name: queue.c
> Author: icebear
> Mail: 3322366195@qq.com
> Created Time: 2023-07-24 21:10:03
> Description: 基于链表的队列实现
************************************************************************/
#include "queue.h"
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    Queue *queue;
    printf("create:\n");
    queue = create();
    printf("size:%3d\n", size(queue));
    printf("isEmpty:%3d\n", isEmpty(queue));
    printf("push: 0-9\n");
    for (int i = 0; i < 10; i++)
    {
        push(queue, i);
    }
    printf("size:%3d\n", size(queue));
    printf("isEmpty:%3d\n", isEmpty(queue));
    printf("pop: 5 item\n");
    for (int i = 0; i < 5; i++)
    {
        printf("%3d\n", pop(queue));
    }
    printf("size:%3d\n", size(queue));
    printf("clear:\n");
    clear(queue);
    printf("isEmpty:%3d\n", isEmpty(queue));
    printf("size:%3d\n", size(queue));
    return 0;
}

Queue *create()
{
    Queue *queue = malloc(sizeof(Queue));
    queue->front = NULL;
    queue->tail = NULL;
    queue->size = 0;
    return queue;
}
void destory(Queue *queue)
{
}
void push(Queue *queue, int item)
{
    if (isEmpty(queue))
    {
        queue->tail = malloc(sizeof(Node));
        queue->tail->data = malloc(sizeof(Data));
        queue->tail->data->value = item;
        queue->front = queue->tail;
        queue->size++;
        return;
    }
    Node *temp = queue->tail;
    queue->tail = malloc(sizeof(Node));
    queue->tail->data = malloc(sizeof(Data));
    queue->tail->data->value = item;
    temp->next = queue->tail;
    queue->size++;
}
int pop(Queue *queue)
{
    if (isEmpty(queue))
    {
        return 0;
    }
    int item = queue->front->data->value;
    Node *temp = queue->front;
    queue->front = queue->front->next;
    free(temp->data);
    free(temp);
    queue->size--;
    if (queue->size == 0 && (queue->tail != NULL))
    {
        queue->tail = NULL;
    }
    return item;
}
int peek(Queue *queue)
{
    if (isEmpty(queue))
    {
        return 0;
    }
    return queue->front->data->value;
}
void clear(Queue *queue)
{
    if (queue->size == 0)
    {
        return;
    }
    Node *temp;
    while (queue->size != 0)
    {
        temp = queue->front;
        queue->front = queue->front->next;
        free(temp->data);
        free(temp);
        queue->size--;
    }
    queue->tail = NULL;
}
int isEmpty(Queue *queue)
{
    if (queue->size == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int size(Queue *queue)
{
    return queue->size;
}